package com.wang.book.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.book.entity.Book;
import com.wang.book.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
// @Controller和@ResponseBody 的组合注解
@RestController
//表示该控制器的所有方法的请求路径都会以 /book 为前缀
@RequestMapping("/books")
public class BookController {
    @Autowired
    private  BookService bookService;

    // 图书分页查询
    @GetMapping
    public ResponseEntity<Page<Book>> listBooks(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        return ResponseEntity.ok(bookService.listBooks(page, size));
    }

    // 新增图书
    @PostMapping
    public ResponseEntity createBook(@Valid @RequestBody Book book) {
        try {
            boolean isAdded = bookService.addBook(book);
            if (isAdded) {
                // 返回 201 Created 状态码，并包含新创建的图书对象
                return ResponseEntity.created(URI.create("/api/books/" + book.getNo())).body(book);
            } else {
                // 返回 400 Bad Request 状态码，并包含错误信息
                return ResponseEntity.badRequest().body("新增失败");
            }
        } catch (Exception e) {
            // 捕获并处理所有异常，返回 500 Internal Server Error 状态码
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("服务器错误: " + e.getMessage());
        }
    }
    //删除图书
    @DeleteMapping("/{id}")
    public ResponseEntity deleteBook(@PathVariable Integer id){
        //删除成功返回200 失败返回404
        return bookService.deleteBook(id) ? ResponseEntity.ok().body("删除成功") : ResponseEntity.status(HttpStatus.NOT_FOUND).body("删除图书不存在");
    }
    //根据id查询图书
    @GetMapping("/{id}")
    public ResponseEntity<Book> getById(@PathVariable Integer id){
       return ResponseEntity.ok(bookService.getBookById(id));
    }
    //更新图书
    @PutMapping
    public ResponseEntity<Book> updateBook(@RequestBody Book book){
        Book updatedBook = bookService.updateBook(book);
        if (updatedBook != null) {
            return ResponseEntity.ok(updatedBook);
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}